"""
合并操作模块
- 合并多个音频文件为一个
- 支持在音频之间插入可选的静音间隙
"""

from pydub import AudioSegment
from typing import List, Optional
from .base_audio import load_audio, save_audio


def merge_audios(input_paths: List[str], output_path: str) -> None:
    """
    简单串接合并多个音频
    """
    if not input_paths:
        return
    merged = load_audio(input_paths[0])
    for p in input_paths[1:]:
        merged += load_audio(p)
    save_audio(merged, output_path)


def merge_audios_with_gaps(input_paths: List[str], output_path: str, gaps_ms: Optional[list] = None) -> None:
    """
    合并多个音频，并在相邻音频之间插入指定时长的静音

    参数:
        gaps_ms: 间隙列表（毫秒），长度应为 len(input_paths) - 1
    """
    if not input_paths:
        return
    merged = load_audio(input_paths[0])
    for i, p in enumerate(input_paths[1:], 1):
        if gaps_ms and i - 1 < len(gaps_ms) and gaps_ms[i - 1] > 0:
            merged += AudioSegment.silent(duration=gaps_ms[i - 1])
        merged += load_audio(p)
    save_audio(merged, output_path)